<script setup lang="ts">
import { ref,watch } from 'vue'
import $api from '@/api/index'
import GoodsFilter from './components/GoodsFilter.vue';
import Search from './components/Search.vue';
import GoodsItem from './components/GoodsItem.vue';
import { useScroll } from '@vueuse/core';
import {useRoute} from 'vue-router'

const $route=useRoute()
const goods=ref([])
const isLoading=ref(true)
let pageNum=1,pageSize=10,hasMore=true
let params:any={}
const getGoods=() =>{
  if(!hasMore) return
  isLoading.value=true
  params.page_num=pageNum
  params.page_size=pageSize
  if($route.query.id){
    params.cate_id=$route.query.id
  }
  const {data:list,loading}=$api.goods.getList(params)
  watch(list,(_list:[]) =>{
    if(_list.length==0) return hasMore=false
    _list.map((item:any) => {
      goods.value.push(item)
    })
  })
  watch(loading,(_loading:boolean) =>{
    isLoading.value=_loading
  })
}
const changeFilter=(val) =>{
  goods.value=[]
  pageNum=1
  hasMore=true
  params={}
  switch(val.value){
    case 'new':
      params.is_new=true
      break
    case 'best':
      params.is_best=true
      break
    case 'spot':
      params.is_on_sale=true
      break
    case 'price':
      params.sort={
        price:val.sort
      }
      break
    case 'sale':
      params.sort={
        total_sell_count:val.sort
      }
      break
  }
  getGoods()
}

const onSearch=(val) =>{
  console.log(val)
}
const target=ref()
const {x,y,arrivedState}=useScroll(target)
watch([x,y],([_x,_y]) =>{
  if(arrivedState.bottom){
    pageNum++
    getGoods()
  }
})
</script>

<template>
  <div ref="target" v-loading="isLoading" 
    w:p="4"
    w:h="full"
    w:overflow="y-scroll"
  >
    <Search @search="onSearch" />
    <GoodsFilter @change="changeFilter" />
    <div v-empty="goods.length">
      <GoodsItem v-for="(item,idx) in goods" :key="item._id" :item="item" />
    </div>
  </div>
</template>

<style scoped lang="scss">

</style>

<route>
{
  meta: {
    title: '搜索'
  }
}
</route>